/**
 * 
 */
package com.study.dao;

import java.util.List;

import org.apache.ibatis.annotations.Many;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.SelectProvider;
import org.apache.ibatis.jdbc.SQL;
import org.apache.ibatis.mapping.FetchType;

import com.study.entity.Student;

/**
 * 关联查询
 * 
 * @author Administrator
 * @date 2019年5月14日
 */
public interface IStudent {

	// 通过注解实现mapper
	// @Select("select s_id id, s_name name from student where class_id=#{id}")
	// id为是否为主键。
	@Results({ @Result(id = true, column = "s_id", property = "id"),
			@Result(column = "s_name", property = "name"), 
			@Result(column = "s_id", property = "majors", many = @Many(select = "com.study.dao.IMajor.getMajorByStuId", fetchType = FetchType.LAZY)), })
	@Select("SELECT * FROM student WHERE s_id =#{id};")
	public List<Student> getStudent(int id);

	
	/**
	 * dao接口中是不能写实现的，所以这里借用内部类来生成动态SQL。
	 * 增改删也有对应的@InsertProvider、@UpdateProvider、@DeleteProvider
	 * @return 
	 * @param student
	 * @return
	 */
	//使用StudentDaoProvider类的findStudentById方法来生成sql  
    @SelectProvider(type = StudentDaoProvider.class, method = "findStudentById")  
	public List<Student> findStudentById(Student student); 
	
    @SelectProvider(type = StudentDaoProvider.class, method = "findStudentById2")  
    public List<Student> findStudentById2(Student student); 
    
    class StudentDaoProvider {  
        public String findStudentById(Student student) {  
            String sql = "SELECT s_id id, s_name name FROM student";  
            if(student.getId() > 0 ){  
                sql += " where s_id = #{id}";  
            } 
//            if(student.getName() != null ){
//            	sql += " where s_name like #{name}";  
//            }   //如果#{id} 和#{name} 同时有值，则sql 会有两个where，查询结果为空
            return sql;  
        }  
        
        public String findStudentById2(Student student) {      
            return new SQL(){{      
                SELECT("s_id id");      
                SELECT("s_name name");      
                FROM("student");      
                if(student.getId() >0){      
                    WHERE("s_id = #{id}");      
                }      
                if(student.getName()!=null){      
                    WHERE("s_name like #{name}");      
                }      
            //从这个toString可以看出，其内部使用高效的StringBuilder实现SQL拼接      
            }}.toString();      
        } 
    }
    
    
}
